package com.codedef.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codedef.entity.JwtParam;
import com.codedef.entity.User;
import com.codedef.mapper.UserMapper;
import com.codedef.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class LoginService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    JwtParam jwtParam;

    public String userLogin(String username, String password) {
        User dbUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (dbUser == null) return null;
        log.info(dbUser.toString());

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(password);
        stringBuilder.insert(1, dbUser.getSalt());
        String passMd5 = DigestUtils.md5Hex(stringBuilder.toString());
        log.info("md5 pass" + passMd5);

        if (passMd5.equals(dbUser.getPassword())) {
            // 用户名密码验证通过
            Integer userId = dbUser.getId();
            // 生成token
            String token = JwtUtil.createToken(userId, jwtParam);

            if (token == null) {
                log.error("===== 用户签名失败 =====");
                return null;
            }
            log.info("===== 用户{}生成签名{} =====", userId, token);

            // 生成用户的签名
            String sign = JwtUtil.getAuthorizationHeader(token);

            // 写Redis数据库
/*            dbUser.setPassword(null);
            dbUser.setSalt(null);
            redisUtil.set(sign, dbUser);*/

            return sign;
        }

        return null;
    }

    public String testDbTime() {
        String dbTime = userMapper.testDbTime();
        System.out.println("dbTime" + dbTime);
        return dbTime;
    }

}
